<template>
	<div class="detail_main">
		<div class="detail_main_top">
			<div class="detail_top_left name">
				<span>{{paperInfo.paperName}}</span>
			</div>
			<span>
				剩余答题时间：<span class="mainColor">{{timeInfo}}</span>
			</span>
			<div class="detail_top_right">
				<el-button type='primary' size='small' :disabled='submitLoad' :loading='submitLoad' @click='openSubmit'>提交试卷</el-button>
			</div>
		</div>
		<div class="detail_main_bottom clearfix">
			<div class="exam_topic">
				<div class="exam_topicstep">
					答题进度：<span class="mainColor">{{overNum}}/{{questions.length}}</span>
				</div>
				<div class="exam_topicitem beautifulScroll">
					<div class="menu_leftlabel" v-if="questionIndex>=0 && questions[questionIndex].questionType == item.value" v-for="(item,index) in questionTypes">
						{{item.name}}<span>（共{{getArray(item.value).length}}题，总分{{getScore(item.value)}}分）</span>
					</div>
					<questionview @checkOver='checkOver' :form="item" :letters="letters" :questionTypes="questionTypes" v-for='(item,index) in questions' v-if="item.questionIndex == questionIndex"></questionview>
				</div>
				<div class="detail_right_control">
					<el-button @click='questionIndex--' type='primary' :disabled='questionIndex<=0' size='small'>上一题</el-button>
					<el-button @click='questionIndex++' type='primary' :disabled='questionIndex>=questions.length-1' size='small'>下一题 </el-button>
				</div>
			</div>
			<div class="menu_detailcard ">
				<div class="exam_info">
					<div class="exam_infoicon">
						<img :src="baseurl + userinfo.headPortraitUrl" v-if="userinfo && userinfo.headPortraitUrl" />
						<img src="@/images/1.png" v-else/>
					</div>
					<div class="exam_infop1">
						姓名：{{userinfo.studentName}}
					</div>
					<div class="exam_infop2">学号：{{userinfo.studentNo}}</div>
				</div>
				<div class="menu_detailcardscroll menu_detailcardscrollleft beautifulScroll">
					<div class="question_types" v-if="getArray(item.value).length" v-for="(item,index) in questionTypes">
						<div class="question_typeinfo">
							{{item.name}}<span>（共{{getArray(item.value).length}}题，总分{{getScore(item.value)}}分）</span>
						</div>
						<div class="question_typenums clearfix">
							<div class="question_typenum" @click="questionIndex = topic.questionIndex" :class='getTopicClass(topic)' v-for="topic in getArray(item.value)">{{topic.indexId}}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="index_mask" v-if='showauto'>
			<div class="auto_cont">
				<div class="auto_contP1">
					<img src="@/images/auto_contP1.png" />系统提示
				</div>
				<div class="auto_contP2">
					考试时间到，系统自动交卷
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { tofixTimeSpent, parseTime } from "@/filters"
	import questionview from "@/components/questions.vue"
	import questionsjs from '@/components/questions.js'
	import { selectStudentDetail } from "@/api/center.js"
	import { savePaperStudyRecord, selectPaperQuestionList, paperStudyDetail, paperCommit } from "@/api/paper.js"
	export default {
		mixins: [questionsjs],
		components: {
			questionview
		},
		data() {
			return {
				userinfo: {},
				paperId: this.$route.query.paperId,
				paperUserAnswerId: '',
				paperInfo: {},
				overNum: 0,
				allOver: false,
				showauto: false,
				submitLoad: false,
				userinfo: {},
				timeInfo: "00:00:00",
				newData: "00:00:00",
				timer: null,
				questions: [],
				questionIndex: -1,
				letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
				nums: ['一', '二', '三', '四', '五', '六', '七', '八', '九'],
				difficultys: [{
					name: '简单',
					value: 'SIMPLE'
				}, {
					name: '中等',
					value: 'MEDIUM'
				}, {
					name: '困难',
					value: 'DIFFICULTY'
				}],
				questionTypes: [{
					name: '单选题',
					value: 'SINGLE'
				}, {
					name: '多选题',
					value: 'MULTIPLE'
				}, {
					name: '判断题',
					value: 'JUDGE'
				}, {
					name: '简答题',
					value: 'SHORT'
				}, {
					name: '病例解析题',
					value: 'ANALYSIS'
				}],
				SINGLE: [],
				MULTIPLE: [],
				JUDGE: [],
				ANALYSIS: [],
				SHORT: [],
				//最初
				SINGLEORI: [],
				MULTIPLEORI: [],
				JUDGEORI: [],
				ANALYSISORI: [],
				SHORTORI: [],
				//试题分数
				SINGLENUM: 0,
				MULTIPLENUM: 0,
				JUDGENUM: 0,
				ANALYSISNUM: 0,
				SHORTNUM: 0,
				//时间
				surplusTime: 3000,
			}
		},
		created() {
			this.getinfo();
			this.getTestDetail();
		},
		mounted() {

		},
		methods: {
			getinfo() {
				selectStudentDetail().then(res => {
					if(res.code == '200') {
						this.userinfo = res.data;
					}
				})
			},
			setRecord() {
				savePaperStudyRecord({
					paperId: this.paperId
				}).then(res => {
					this.paperUserAnswerId = res.data
				})
			},
			getTestDetail() {
				paperStudyDetail({
					paperId: this.paperId
				}).then(res => {
					if(res.data.paperStatus == 1) {
						this.setBack('当前考试未开始，请稍后重试！')
						return
					}
					if(res.data.paperStatus == 2) {
						if(res.data.submitStatus == 1) {
							this.setBack('您已提交，请勿重复参加！')
							return
						} else {
							this.paperInfo = res.data;
							this.surplusTime = this.paperInfo.duration * 60;
							this.getTest()
							this.setRecord();
						}
					}
					if(res.data.paperStatus == 3) {
						this.setBack('当前考试已结束，无法参加！')
						return
					}
				})
			},
			setBack(message) {
				this.$alert(message, '提示', {
					confirmButtonText: '确定',
					type: 'warning'
				}).then(() => {
					this.$router.back(-1);
				}).catch(() => {
					this.$router.back(-1);
				})
			},
			getTest() {
				selectPaperQuestionList({
					paperId: this.paperId
				}).then(res => {
					if(res.code == '200') {
						var questions = res.data || []
						this.getInfoList(questions)
					}
				})
			},
			getInfoList(questions) {
				var questionIndex = -1;
				questions.map((item, index) => {
					var indexId = this[item.questionType + "ORI"].length + 1;
					questionIndex++;
					var optionObject = {};
					var optionsArr = [];
					var options = item.options;
					if(options) {
						optionObject = JSON.parse(options);
						optionsArr = Object.values(optionObject);
					}
					var userAnswer = item.userAnswer || '';
					var userAnswers = [];
					if(userAnswer) {
						userAnswers = userAnswer.split('');
					}
					var topic = Object.assign({}, item, {
						paperId: this.paperId,
						indexId: indexId,
						questionIndex: questionIndex,
						score: item.score || 0,
						questionScore: item.questionScore || 0,
						optionsArr: optionsArr,
						userAnswer: userAnswer,
						userAnswers: userAnswers,
						overed: userAnswer ? true : false, //是否已经答题
					})
					this.pushList(topic);
					this[item.questionType + 'ORI'].push(item)
				})
				this.questionIndex = 0;
				this.$nextTick(() => {
					this.setExamTime();
					this.spendTime();
				})
			},
			spendTime() {
				var timer = this.timer;
				if(timer) {
					clearInterval(timer);
				}
				var newTimer = setInterval(() => {
					this.setExamTime();
					this.surplusTime--;
					if(this.surplusTime <= 0) {
						this.autoSend();
					}
				}, 1000);
				this.timer = newTimer;
			},
			setExamTime() {
				var newData = new Date();
				this.newData = parseTime(newData, '{y}-{m}-{d} {h}:{i}:{s}')
				var surplusTime = this.surplusTime;
				var timeSecond = surplusTime > 0 ? surplusTime : 0;
				this.timeInfo = tofixTimeSpent(timeSecond);
			},
			checkOver() {
				var overNum = 0;
				var allOver = true;
				var questions = this.questions;
				questions.map(item => {
					if(!item.overed) {
						allOver = false
					}else{
						overNum ++ 
					}
				})
				this.overNum = overNum;
				this.allOver = allOver;
			},
			autoSend() {
				var timer = this.timer;
				if(timer) {
					clearInterval(timer);
					this.timer = null;
				}
				this.showauto = true;
				this.allSubmit()
			},
			openSubmit() {
				var message = this.allOver ? '交卷后，将不能再次作答或者修改答案' : '您还有试题未作答，交卷后将不能再次作答或者修改答案';
				this.$confirm(message, '确认提交考试？', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.allSubmit()
				}).catch(() => {});
			},
			allSubmit() {
				this.submitLoad = true;
				var data = {
					paperId: this.paperId,
					paperUserAnswerId: this.paperUserAnswerId,
					questionList: this.questions,
				}
				paperCommit(data).then(res => {
					if(res.code == '200') {
						setTimeout(_ => {
							this.showmask = false;
							this.showauto = false;
							this.submitLoad = false;
							this.$message({
								type: 'success',
								message: res.message
							})
							this.$router.back(-1);
						}, 1500)
					} else {
						this.showmask = false;
						this.showauto = false;
						this.submitLoad = false;
						this.$message({
							type: 'error',
							message: res.message
						})
					}
				})
			},
		},
		beforeRouteLeave(to, from, next) {
			var timer = this.timer;
			if(timer) {
				clearInterval(timer);
				this.timer = null;
			}
			next();
		},
	}
</script>